import {  Modal,message } from 'antd';
import React, { createRef, useImperativeHandle, useState } from 'react';
import { request } from 'umi';
import FormComp from './c_form';

const App: React.FC<cType.dioProTp> = React.forwardRef((props,ref) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [formData, setFormData] = useState({});
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const dioOption=props.formOption.dioOption
  const cformRef:any=createRef()
  const showModal = (data:any) => {
    setFormData(data)
    setOpen(true);
  };
  useImperativeHandle(ref,()=>({showModal:showModal}))
  const handleOk =async () => {
    setConfirmLoading(true);
    cformRef.current.ref.current.validateFields().then(async(res:any)=>{
      console.log(res);
      let msg
      if(formData.id){
         msg = await request(props.formOption.formOption.saveUrl,{data:{...res,id:formData.id},method:"put"});
      }else{
         msg = await request(props.formOption.formOption.saveUrl,{data:res,method:"post"});
      }
    if (msg.flag) {
      setOpen(false);
     messageApi.success('提交成功!');
      await props.getUserTable()
      setConfirmLoading(false);
    }
   }).catch(async(err:any)=>{
    console.log(err);
    setConfirmLoading(false);
   })
  };
  const handleCancel = () => {
    setOpen(false);
  };
  const formDataPro:cType.formProTp={
    formData:formData,
    formOption:props.formOption.formOption
  }
  return (
    <div>
     {contextHolder}
      {open && (
        <Modal
          title={dioOption.title}
          open={open}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
          width={dioOption.dioWidth||600}
        >
          <FormComp {...formDataPro} ref={cformRef}></FormComp>
        </Modal>
      )}
    </div>
  );
})
export default App;
